package com.idgenerator;

import com.idgenerator.configuration.IdGeneratorProperties;
import com.idgenerator.exception.IdGeneratorException;
import com.idgenerator.generator.IdGenerator;
import lombok.Getter;
import lombok.Setter;

import java.util.List;
import java.util.Optional;

@Getter
@Setter
public class IdGeneratorService {

    List<List<? extends IdGenerator>> idGeneratorList;

    private IdGeneratorProperties idGeneratorProperties;
    /**
     * 获取对应的ID生成器
     */
    public IdGenerator getDefaultIdGenerator() {
        return getIdGenerator(idGeneratorProperties.getDefaultGen());
    }
    /**
     * 获取对应的ID生成器
     */
    public IdGenerator getIdGenerator(String gen) {
        Optional.ofNullable(idGeneratorProperties.getEnable())
                .filter(e->e)
                .orElseThrow(()->new IdGeneratorException("设置spring.id.enable=true,开启ID生成器"));
        for (List<? extends IdGenerator> idGenerators : idGeneratorList) {
            for (IdGenerator idGenerator : idGenerators) {
                if (idGenerator.getGen().equals(gen)) {
                    return idGenerator;
                }
            }
        }
        throw new IdGeneratorException("没有寻找到可用的ID生成器");
    }


}
